/**
 * Handles saving data into localStorage
 */

app.factory("storageService", ['$http', function($http){
   var storageService = {};
   var baseUri = "http://niisku.lamk.fi/~laskiga/json/";
   
   storageService.updatedAt = function(item){
       if(item){
           return localStorage.getItem(item + '_updated');
       } else {
           return false;
       }
   };
   
   storageService.getItem = function(item){
        if(item){
            var jsonObject = JSON.parse(localStorage.getItem(item));
            return jsonObject;
        }
        return false;
   };
   
   storageService.getById = function(item, id){
        var items = this.getItem(item);
        if(items){
            id = id - 1;
            return items[id];
        }
       return false;
   };
   
   storageService.firstRun = function(){
        if(localStorage.getItem("run") === null){
            var items = [
                "foods",
                "events",
                "venues",
                "days",
                "races/Nordic Combined/1",
                "races/Nordic Combined/0",
                "races/Ski Jumping/1",
                "races/Ski Jumping/0",
                "races/Cross-Country/0"
            ];
            for(var i in items){
                this.updateData(items[i]);
            }
            localStorage.setItem("run", "done");
        }
   };
   
   storageService.updateData = function(q){
        return $http.get(baseUri + q).success(function(data){
            localStorage.setItem(q, JSON.stringify(data));
            var updated = q + "_updated";
            storageService.dataUpdated(q).then(function(results){
               localStorage.setItem(updated, results.data); 
            });
            return data;
        });
   };
   
   storageService.dataUpdated = function(q){
        return $http.get(baseUri + "updated/" + q).success(function(results){
            return results;
        });
   };

   return storageService;
}]);